package com.goscom.app.deeset;

import java.util.ArrayList;
import com.goscom.app.database.DBAdapter;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {

	private EditText mEdtUser, mEdtPass;
	private DBAdapter mDB;
	private SharedPreferences sharedPref;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		mEdtUser = (EditText) findViewById(R.id.edtLoginUser);
		mEdtPass = (EditText) findViewById(R.id.edtLoginPass);

		sharedPref = getSharedPreferences("DEESET", Context.MODE_PRIVATE);

		mDB = new DBAdapter(Login.this);
		mDB.open();
		
	}

	public void Login(View v) {
		if (mEdtUser.getText().toString().equals("") == true
				|| mEdtPass.getText().toString().equals("") == true) {
			Toast.makeText(Login.this, "Please fill username or password!",
					Toast.LENGTH_LONG).show();
		} else {
			ArrayList<ContentValues> arlstCont = new ArrayList<ContentValues>();
			arlstCont = mDB.queryAllUser();
			int i = 0;
			for (; i < arlstCont.size(); i++) {
				ContentValues content = arlstCont.get(i);
				if (mEdtUser.getText().toString()
						.equals(content.getAsString("username")) == true
						&& mEdtPass.getText().toString()
								.equals(content.getAsString("password")) == true) {
					setStringPref(sharedPref, "userid", "1");
					if (mDB != null) {
						mDB.close();
					}
					startActivity(new Intent(Login.this, Welcome.class));
					break;
				}
			}
			if (i == arlstCont.size()) {
				Toast.makeText(Login.this, "Username or password incorrect!",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	public String getStringPref(SharedPreferences sharedPref, String name,
			String valrtn) {
		return sharedPref.getString(name, valrtn);
	}

	public void setStringPref(SharedPreferences sharedPref, String name,
			String value) {
		SharedPreferences.Editor editor = sharedPref.edit();
		editor.putString(name, value);
		editor.commit();
	}

	@Override
	protected void onRestart() {
		mDB.open();
		super.onRestart();
	}

	@Override
	protected void onDestroy() {
		if (mDB != null) {
			mDB.close();
		}
		super.onDestroy();
	}
}
